/*
 * @Author: ૮₍ ˙О˙₎ა
 * @Date: 2023-07-14 18:55:26
 */
import { useUserInfoStore } from '@/stores/userInfo'
import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus'

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 5000
})
// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么

    const useInfoStore = useUserInfoStore()
    const token = useInfoStore.token
    if (token && config.headers) {
      config.headers.token = token
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    const res = response.data
    if (res.code !== 200 && res.code !== 20000) {
      if (res.code === 20001) {
        ElMessage.closeAll()
        // token过期
        ElMessage({
          type: 'error',
          message: 'token过期,请重新登录',
          duration: 5000
        })
        // 获取userInfoStore实例
        const userInfoStore = useUserInfoStore()
        userInfoStore.reset()
      } else {
        ElMessage({
          type: 'error',
          message: res.message,
          duration: 5000
        })
      }
      return Promise.reject(new Error(res.message || 'error'))
    } else {
      return res
    }
  },
  function (error) {
    ElMessage({
      type: 'error',
      message: error,
      duration: 5000
    })
    return Promise.reject(error)
  }
)

export interface reqDataRes<T> {
  code: number
  data: T
  message: string
  success: boolean
}

const http = <T>(url: string, method: Method, data?: unknown) => {
  const newMethod = method.toLocaleUpperCase()
  return instance.request<reqDataRes<T>, reqDataRes<T>>({
    url,
    method: newMethod,
    params: newMethod === 'GET' ? data : {},
    data: newMethod === 'POST' || method === 'PUT' || method === 'DELETE' ? data : {}
  })
}

export { http }
